//
//  SmallPlayViewController.m
//  Dayou
//
//  Created by mac on 2018/8/14.
//  Copyright © 2018年 YangYang. All rights reserved.
//

#import "SmallPlayViewController.h"
#import "VideoPlayListTableViewCell.h"

#import <ZFPlayer.h>
#import <ZFAVPlayerManager.h>
#import <ZFPlayerControlView.h>
#import <ZFIJKPlayerManager.h>

@interface SmallPlayViewController ()<UITableViewDelegate,UITableViewDataSource,VideoPlayCellDelegate>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) ZFPlayerController *playerController;
@property (nonatomic, strong) ZFPlayerControlView *controlView;
@property (nonatomic, strong) NSMutableArray *dataSource;
@property (nonatomic, strong) NSMutableArray *videoURLs;

@end

@implementation SmallPlayViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self createTable];
    [self initPlayView];
    [self requestNetData];
}
-(void)createTable
{
    [self.view addSubview:self.tableView];
}
#pragma mark - ----------------------列表自动播放需要实现的方法----------------------
-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    WeakSelf;
    [_tableView zf_filterShouldPlayCellWhileScrolled:^(NSIndexPath * _Nonnull indexPath) {
        StrongObj(weakSelf);
        [StrongweakSelf playTheVideoAtIndexPath:indexPath scrollToTop:NO];
    }];
}

-(void)initPlayView
{
    ZFAVPlayerManager *playerManager = [[ZFAVPlayerManager alloc] init];
    /// player的tag值必须在cell里设置
    self.playerController = [ZFPlayerController playerWithScrollView:self.tableView playerManager:playerManager containerViewTag:100];
    self.playerController.controlView = self.controlView;
    //    self.playerController.shouldAutoPlay = YES;
    /// 移动网络依然自动播放
    //    self.playerController.WWANAutoPlay = YES;
    /// 0.8是消失80%时候，默认0.5
    //    self.playerController.playerDisapperaPercent = 1.0;
    WeakSelf;
    self.playerController.orientationWillChange = ^(ZFPlayerController * _Nonnull player, BOOL isFullScreen) {
        
    };
    
    self.playerController.playerDidToEnd = ^(id<ZFPlayerMediaPlayback>  _Nonnull asset) {
        StrongObj(weakSelf);
        [StrongweakSelf.controlView resetControlView];
        [StrongweakSelf.playerController stopCurrentPlayingCell];
        
        
//        [StrongweakSelf.tableView zf_filterShouldPlayCellWhileScrolled:^(NSIndexPath * _Nonnull indexPath) {
//            [StrongweakSelf playTheVideoAtIndexPath:indexPath scrollToTop:NO];
//        }];
//        StrongObj(weakSelf);
//        if (StrongweakSelf.playerController.playingIndexPath.row < StrongweakSelf.videoURLs.count - 1 && !StrongweakSelf.playerController.isFullScreen) {
//            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:self.playerController.playingIndexPath.row + 1 inSection:0];
//            [StrongweakSelf playTheVideoAtIndexPath:indexPath scrollToTop:YES];
//        }
//        else if (StrongweakSelf.playerController.isFullScreen)
//        {
//            [StrongweakSelf.playerController stopCurrentPlayingCell];
//        }
    };
    
    #pragma mark - ----------------------以下设置滑出屏幕后不停止播放----------------------
    self.playerController.stopWhileNotVisible = NO;
    CGFloat margin = 20;
    CGFloat w = ScreenWidth/2;
    CGFloat h = w * 9/16;
    CGFloat x = ScreenWidth - w - margin;
    CGFloat y = ScreenHeight - h - margin;
    self.playerController.smallFloatView.frame = CGRectMake(x, y, w, h);
}

-(void)requestNetData
{
    NSString *path = [[NSBundle mainBundle] pathForResource:@"data" ofType:@"json"];
    NSData *data = [NSData dataWithContentsOfFile:path];
    NSDictionary *dataDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
    NSArray *videoList = dataDic[@"list"];
    [self.dataSource addObjectsFromArray:[CellModel mj_objectArrayWithKeyValuesArray:videoList]];
    [_tableView reloadData];
    NSLog(@"dataDic = %@",dataDic);
    for (CellModel *model in self.dataSource) {
        [self.videoURLs addObject:[NSURL URLWithString:model.video_url]];
    }
    self.playerController.assetURLs = self.videoURLs;
    NSLog(@"videoURLs = %@",self.videoURLs);
}

#pragma mark - ----------------------VideoPlayCellDelegate----------------------
-(void)playTheVideoAtIndexPath:(NSIndexPath *)indexPath
{
    [self playTheVideoAtIndexPath:indexPath scrollToTop:NO];
}

- (void)playTheVideoAtIndexPath:(NSIndexPath *)indexPath scrollToTop:(BOOL)scrollToTop {
    NSLog(@"开始播放");
    [self.playerController playTheIndexPath:indexPath scrollToTop:scrollToTop];
    CellModel *model = self.dataSource[indexPath.row];
    [self.controlView showTitle:model.title
                 coverURLString:model.thumbnail_url
                 fullScreenMode:ZFFullScreenModeLandscape];
}

#pragma mark - ----------------------UITableViewDataSource----------------------
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    VideoPlayListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"VideoPlayListTableViewCell"];
    if (!cell) {
        cell = [[VideoPlayListTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"VideoPlayListTableViewCell"];
    }
    if (self.dataSource.count > indexPath.row) {
        CellModel *model = self.dataSource[indexPath.row];
        [cell setDelegate:self withIndePath:indexPath];
        cell.model = model;
    }
    return cell;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataSource.count;
}

#pragma mark - ----------------------UITableViewDelegate----------------------
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CellModel *model = self.dataSource[indexPath.row];
    return model.cellHeight;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
}

#pragma mark - ----------------------懒加载----------------------
-(UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight) style:UITableViewStylePlain];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.tableFooterView = [UIView new];
        WeakSelf;
        _tableView.zf_scrollViewDidStopScrollCallback = ^(NSIndexPath * _Nonnull indexPath) {
            StrongObj(weakSelf);
            [StrongweakSelf playTheVideoAtIndexPath:indexPath scrollToTop:NO];
        };
    }
    return _tableView;
}

-(ZFPlayerControlView *)controlView
{
    if (!_controlView) {
        _controlView = [ZFPlayerControlView new];
    }
    return _controlView;
}

-(NSMutableArray *)videoURLs
{
    if (!_videoURLs) {
        _videoURLs = [NSMutableArray new];
    }
    return _videoURLs;
}

-(NSMutableArray *)dataSource
{
    if (!_dataSource) {
        _dataSource = [NSMutableArray new];
    }
    return _dataSource;
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.playerController stopCurrentPlayingCell];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
